#include "TimerService.h"
#include "SoundService.h"
#include "log.h"

TimerService::TimerService(QObject *parent)
    : QObject(parent)
    , m_timer(new QTimer(this))
    , m_state(TimerState::Stopped)
    , m_mode(TimerMode::Countdown)
    , m_totalDurationMs(0)
    , m_elapsedMs(0)
    , m_alarm1Triggered(false)
    , m_alarm2Triggered(false)
    , m_alarm3Triggered(false)
    , m_timeoutTriggered(false)
{
    // 设置计时器间隔为10ms，提供更精确的计时
    m_timer->setInterval(10);
    
    // 连接计时器信号
    connect(m_timer, &QTimer::timeout, this, &TimerService::onTimerTick);
    
    logInfo("TimerService 初始化完成");
}

TimerService::~TimerService()
{
    if (m_timer->isActive()) {
        m_timer->stop();
    }
    logInfo("TimerService 销毁");
}

TimerService& TimerService::instance()
{
    static TimerService instance;
    return instance;
}

void TimerService::startTimer(int durationMs, TimerMode mode)
{
    if (m_state == TimerState::Running) {
        logWarning("计时器已在运行中，无法重新启动");
        return;
    }

    m_totalDurationMs = durationMs;
    m_mode = mode;
    m_elapsedMs = 0;
    
    // 重置报警标记
    m_alarm1Triggered = false;
    m_alarm2Triggered = false;
    m_alarm3Triggered = false;
    m_timeoutTriggered = false;
    
    // 启动计时器
    m_timer->start();
    changeState(TimerState::Running);
    
    logInfo("计时器启动 - 时长:" << durationMs << "ms, 模式:" 
            << (mode == TimerMode::Countdown ? "倒计时" : "正计时"));
}

void TimerService::pauseTimer()
{
    if (m_state != TimerState::Running) {
        logWarning("计时器未在运行中，无法暂停");
        return;
    }

    m_timer->stop();
    changeState(TimerState::Paused);
    logInfo("计时器已暂停");
}

void TimerService::resumeTimer()
{
    if (m_state != TimerState::Paused) {
        logWarning("计时器未暂停，无法恢复");
        return;
    }

    m_timer->start();
    changeState(TimerState::Running);
    logInfo("计时器已恢复");
}

void TimerService::stopTimer()
{
    if (m_state == TimerState::Stopped) {
        return;
    }

    m_timer->stop();
    m_elapsedMs = 0;
    changeState(TimerState::Stopped);
    logInfo("计时器已停止");
}

void TimerService::resetTimer()
{
    stopTimer();
    m_elapsedMs = 0;
    m_alarm1Triggered = false;
    m_alarm2Triggered = false;
    m_alarm3Triggered = false;
    m_timeoutTriggered = false;
    logInfo("计时器已重置");
}

void TimerService::setAlarms(const TimerConfig& config)
{
    m_alarmConfig = config;
    logDebug("报警配置已更新");
}

int TimerService::getRemainingMs() const
{
    if (m_mode == TimerMode::Countdown) {
        return qMax(0, m_totalDurationMs - m_elapsedMs);
    } else {
        // 正计时模式，剩余时间为已用时间
        return m_elapsedMs;
    }
}

int TimerService::getElapsedMs() const
{
    return m_elapsedMs;
}

int TimerService::getTotalDurationMs() const
{
    return m_totalDurationMs;
}

TimerService::TimerState TimerService::getState() const
{
    return m_state;
}

TimerMode TimerService::getMode() const
{
    return m_mode;
}

bool TimerService::isRunning() const
{
    return m_state == TimerState::Running;
}

void TimerService::onTimerTick()
{
    // 增加已用时间
    m_elapsedMs += 10;
    
    // 计算当前值
    int currentMs = (m_mode == TimerMode::Countdown) 
                    ? (m_totalDurationMs - m_elapsedMs) 
                    : m_elapsedMs;
    
    // 发出滴答信号
    emit timerTick(getRemainingMs(), m_elapsedMs);
    
    // 检查报警
    if (m_mode == TimerMode::Countdown) {
        checkAlarms(currentMs);
    }
    
    // 检查是否完成（倒计时模式）
    if (m_mode == TimerMode::Countdown && currentMs <= 0) {
        m_timer->stop();
        changeState(TimerState::Finished);
        emit timerFinished();
        logInfo("倒计时完成");
    }
    
    // 检查超时（倒计时模式）
    if (m_mode == TimerMode::Countdown && 
        m_alarmConfig.isTimeoutEnabled && 
        !m_timeoutTriggered &&
        currentMs <= -m_alarmConfig.timeoutMs) {
        m_timeoutTriggered = true;
        emit alarmTriggered(TipType::TIMEOUT);
        logInfo("超时报警触发");
    }
}

void TimerService::checkAlarms(int currentMs)
{
    // 检查报警1
    if (m_alarmConfig.isAlarm1Enabled && 
        !m_alarm1Triggered && 
        currentMs <= m_alarmConfig.alarm1Ms) {
        m_alarm1Triggered = true;
        emit alarmTriggered(TipType::ALARM1);
        logInfo("报警1触发: " << m_alarmConfig.alarm1Ms << "ms");
    }
    
    // 检查报警2
    if (m_alarmConfig.isAlarm2Enabled && 
        !m_alarm2Triggered && 
        currentMs <= m_alarmConfig.alarm2Ms) {
        m_alarm2Triggered = true;
        emit alarmTriggered(TipType::ALARM2);
        logInfo("报警2触发: " << m_alarmConfig.alarm2Ms << "ms");
    }
    
    // 检查报警3
    if (m_alarmConfig.isAlarm3Enabled && 
        !m_alarm3Triggered && 
        currentMs <= m_alarmConfig.alarm3Ms) {
        m_alarm3Triggered = true;
        emit alarmTriggered(TipType::ALARM3);
        logInfo("报警3触发: " << m_alarmConfig.alarm3Ms << "ms");
    }
}

void TimerService::changeState(TimerState newState)
{
    if (m_state != newState) {
        m_state = newState;
        emit stateChanged(newState);
        logDebug("计时器状态改变: " << (int)newState);
    }
}
